package edu.utexas.mapreduce;

import java.util.Stack;
import java.util.TreeMap;
import java.util.Vector;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class JobContentHandler extends DefaultHandler {

	private Stack<String> stack = new Stack<String>();
	private TreeMap<String, String> keyMap = new TreeMap<String, String>();
	private Vector<TreeMap<String, String>> requests = new Vector<TreeMap<String, String>>();

	
	private String key;
	
	public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException {
		if(localName.equals(JobRequest.requestKey))
				return;
		stack.push(localName);
		keyMap.put(genKey(), "");
	}
	
	public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException { 
		if(genKey().equals(Job.jobKey)){
			//done parsing one job
			requests.add(keyMap);
			stack.removeAllElements();
			keyMap = new TreeMap<String, String>();
		}
		else{
			if(localName.equals(JobRequest.requestKey))
				return;
			stack.pop();
		}
	}
	  
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (stack.empty())
			return;
		key = genKey();
		keyMap.put(key, keyMap.get(key) + new String(ch,start,length));
	}
	  
	public Vector<TreeMap<String, String>> getRequest() {
		return requests;
  }
	
	private  String genKey(){
		if (stack.size()>0){
			String key = "";
			for(int i =0;i<stack.size();i++){
				key = key + "_" + stack.elementAt(i);
			}
			return key;
		}
		else
			return "bad_state";
	}
}
